#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

const std::string fifo_path = "./myfifo";
#define DeFault -1
#define Creater 1
#define User 2
#define Write O_WRONLY
#define Read O_RDONLY

#define BaseSize 4096

class namedpipe
{
    bool OpenNamePipe(int flags)
    {
        _fd = open(_fifo_path.c_str(), flags);
        if (_fd < 0)
        {
            perror("open");
            return false;
        }
        return true;
    }

public:
    namedpipe(std::string fifo_path, int id)
        : _fifo_path(fifo_path), _id(id), _fd(DeFault)
    {
        if (_id == Creater)
        {
            int res = mkfifo(_fifo_path.c_str(), 0666);
            if (res < 0)
            {
                perror("mkfifo");
            }
            std::cout << "Creater create namedpipe" << std::endl;
        }
    }

    bool OpenForRead()
    {
        return OpenNamePipe(Read);
    }

    bool OpenForWrite()
    {
        return OpenNamePipe(Write);
    }

    int ReadNamedPipe(std::string *out)
    {
        char buf[BaseSize];
        int res = read(_fd, buf, sizeof(buf));
        if (res > 0)
        {
            buf[res] = 0;
            *out = buf;
        }
        return res;
    }

    int WriteNamedPipe(const std::string &in)
    {
        return write(_fd, in.c_str(), in.size());
    }

    ~namedpipe()
    {
        if (_id == Creater)
        {
            int res = unlink(_fifo_path.c_str());
            if (res < 0)
            {
                perror("unlink");
            }
            std::cout << "Creater delete namedpipe" << std::endl;
        }
        if (_fd != DeFault)
            close(_fd);
    }

private:
    const std::string _fifo_path;
    int _id; // 标明身份,是创造者还是使用者
    int _fd; // 文件描述符,命名管道本质还是复用文件系统的代码
};